import PayRollsAPI from '../../../../common/api/salary/payrolls/payrolls.api.js';
import doT from '../../../../../vendor/template/doT.js';
import { auditStateToHtml } from "../../../../common/json-mapping/state-content-mapping.js";
import watermark from '../../../../common/watermark.js';
import { getAuthZ, TEST_NUMBER, TEST_INFO_NUMBER, Collaboration_APP, Service_APP } from '../../../../../../public/js/config/config.js';

(function (window, document, $) {
    const _isNothing = `<div class="weui-loadmore weui-loadmore_line">
			<span class="weui-loadmore__tips">暂无数据</span>
			</div>`;
    const payrollsmainTemplate = doT.template($('#payrollsmain-template').text());
    let _vm, _res, operatarr = [], index, resTotal = [], listindex = "";
    let _page = {
        pageSize: 12,
        pageIndex: 0,
        totalPages: -1,
    }
    $(function () {
        window.sessionStorage.removeItem('getEntryInfo')
        window.sessionStorage.removeItem('mainInfo')
        _vm = new Vue({
            el: "#payrollsmain",
            data() {
                return {
					main:{
						"year" : getUrlKey("year") == undefined ? 2023 : Number(getUrlKey("year"))
					},
                    payrollsList: [],
                    page: { ..._page }
                }
            },
            computed: {
                rgb() {
                    return `111`
                }
            }
        });
		watermarkBgImg(); // 水印
        _initDataTable();
        _initCommand();
        _initSlide();
        // _ctlReturn();
        pullLoad();
        _returnMain();
        liststatues();
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
    });

    //TODO : 命名初始化
    const _initCommand = () => {
        // 点击功能可视区之外的区域
        $(document).bind("click", function (e) {
            var target = $(e.target);
            if (target.closest(".saleElp").length == 0) { //点击可视区域.saleElp之外的地方触发
                $(".saleElp").siblings('.detail').css('display', 'none')
            }
            // 点击整行跳转详情页面
            $(document).on('click', '.looksale', function (e) {
                $(document).off("click", ".looksale")
                index = $(this).index()
                location.href = `../payrolls/payrollsdetails.html?v=${Utils.GetTime()}&id=${resTotal[index].id}&Y=${resTotal[index].year}&M=${resTotal[index].month}&F=${resTotal[index].freq}`;
            })
        })
        // 点击整行跳转详情页面
        $(document).on('click', '.looksale', function (e) {
            e.stopPropagation()
            $(document).off("click", ".looksale")
            index = $(this).index()
            location.href = `../payrolls/payrollsdetails.html?v=${Utils.GetTime()}&id=${resTotal[index].id}&Y=${resTotal[index].year}&M=${resTotal[index].month}&F=${resTotal[index].freq}`;
        });
		// 点击左侧按钮
		$('#leftBtn').on('click', function () {
			if(_vm.main.year > 1970){
				_vm.main.year = _vm.main.year - 1
				_initPage();
				_initDataTable(true);
			}
		});
		// 点击右侧按钮
		$('#rightBtn').on('click', function () {
			let nowyear = new Date().getFullYear()
			if(_vm.main.year < nowyear){
				_vm.main.year = _vm.main.year + 1
				_initPage();
				_initDataTable(true);
			}
		});
		//返回公众号主页
		$(document).on('click', '#returnPage', function (e) {
		    location.href = `../../../main.html`;
		})

    }
   
    // 导航栏
    const liststatues = () => {
        $('#spleplan-navbar a').on('click', function () {
            listindex = Number($(this).index());
            $(this).addClass('weui-bar__item--on').siblings().removeClass('weui-bar__item--on');
            if (listindex === 0) {
                listindex = ""
            }
            _initPage();
            _initDataTable();
        })
    }
    // 请求列表数据
    const _initDataTable = (flag) => {
        let _data = _vm.page;
        PayRollsAPI.seachPayRolls(Object.assign({
            searchInfo: "",
			y: _vm.main.year,
            Sort: "",
            BillStatus: listindex
        }, _data)).then(res => {
			if(!flag){
				_page = {
				    pageSize: 12,
				    pageIndex: _data.pageIndex + 1,
				    totalPages: res.totalPages
				}
				_vm._data.page = Object.assign({}, _page);
			}else {
				_page = {
				    pageSize: 12,
				    pageIndex: 1,
				    totalPages: res.totalPages,
				}
				_vm._data.page = Object.assign({}, _page);
			}
            _res = res.items
			_res.forEach(ele => {
			    // 数字转换货币格式
			    ele.totalPaid = Utils.toThousands(ele.totalPaid);
			})
			if(flag) resTotal=[];
			// if(_page.pageIndex == 0) resTotal=[]; //当查询的数据是第一页的时候清空缓存的查询结果队列
            resTotal.push(..._res);
            _vm.payrollsList = []
            _vm.payrollsList = [..._vm.payrollsList, ...resTotal];
            $('.looksale:last').css('margin-bottom', '10px')
            $('#payrollstel').empty().append(payrollsmainTemplate(_vm.payrollsList));
            $('.looksale').eq(0).find('.saledetail').each(function (index, domele) {
                operatarr = $(domele).text().trim().split(' ')
            })
            $('.looksale:last').css('margin-bottom', '120px')
        });
    }
    // 下拉加载
    const _initSlide = () => {
        //分别设置滑动距离，开始位置，结束位置，和模拟数据的定时器
        let disY, startY, endY, timer, t, pullheight;
        // 触摸开始
        $('#payrollstel').on('touchstart', function (e) {
            startY = e.originalEvent.changedTouches[0].pageY;//开始时的坐标
        });
        // 移动中
        $('#payrollstel').on('touchmove', function (e) {
            $(".saleElp").siblings('.detail').css('display', 'none')
            // 点击整行跳转详情页面
            $(document).on('click', '.looksale', function (e) {
                $(document).off("click", ".looksale");
                index = $(this).index();
                location.href = `../payrolls/payrollsdetails.html?v=${Utils.GetTime()}&id=${resTotal[index].id}&Y=${resTotal[index].year}&M=${resTotal[index].month}&F=${resTotal[index].freq}`;
                
            })
            endY = e.originalEvent.changedTouches[0].pageY;
            disY = endY - startY;//移动后的坐标减去开始坐标，滑动距离。
            if (isTop() && disY > 0) {
                e.preventDefault();
            }
            if (disY < 60) {
                $('#pull-down').css({
                    height: disY + 'px'//父盒子的高度随着滑动距离变化，有最大值。
                });
            } else {
                $('#pull-down').css({
                    height: 60 + 'px'//父盒子的最大高度
                });
            }
            // 结束时
            $('#payrollstel').on('touchend', function (e) {
                clearInterval(timer);
                endY = e.originalEvent.changedTouches[0].pageY;
                disY = endY - startY;
                if (isTop() && disY > 0) {
                    timer = setInterval(function () {
                        $('#pull-down').css({
                            height: 0 + 'px',//松手后的返回。
                        });
                        clearInterval(timer);
                        _initPage()
                        _initDataTable(false);//加载数据 
                    }, 300)
                } else {
                    $('#pull-down').css({
                        height: 0 + 'px',//松手后的返回。
                    });
                }
                $('#payrollstel').off('touchend')
            })
        });
    }
    const isTop = () => {
        var t = document.documentElement.scrollTop || document.body.scrollTop;
        return t === 0 ? true : false;
    }

    //TODO : 上拉加载
    const pullLoad = () => {
        // 监听滚动的父容器
        $("body").infinite().on("infinite", function () {
            let _data = _vm._data.page;
            if (_data.pageIndex == _data.totalPages) return;
            let self = this;
            if (self.loading) return;
            self.loading = true;
            setTimeout(function () {
                _initDataTable(false);
                self.loading = false;
            }, 500);   //模拟延迟
        });
    }
    // 控制返回按钮，返回的页面
    const _ctlReturn = () => {
        if (window.history && window.history.pushState) {
            history.pushState(null, null, document.URL);
            window.addEventListener('popstate', function () {
                history.pushState(null, null, document.URL);
                //跳转列表
                this.window.location = `../main.html`;
            });
        }
    }
    //返回首页
    const _returnMain = () => {
        $('#returnMain').on('click', function () {
            location.href = `../main.html`;
        });
    }

    // 初始化分页
    const _initPage = () => {
        resTotal = []
        _page = {
            pageSize: 12,
            pageIndex: 0,
            totalPages: -1,
        }
        _vm._data.page = Object.assign({}, _page);
    }
    // 千分位
    const format = (num) => {
        var reg = /\d{1,3}(?=(\d{3})+$)/g;
        return (num + '').replace(reg, '$&,');
    }
	
	const watermarkBgImg = () => {
	    let _userInfo = JSON.parse(Utils.GetSessionStorage("SNLoginUserInfo")) || {};
	    PayRollsAPI.queryUserName(Utils.GetQueryString('state') || Collaboration_APP.sourceID).then(res => {
	        watermark.set(_userInfo.curUserName + res.code);// 水印
	    }).catch(_ => {
	        watermark.set(_userInfo.curUserName);// 水印
	    });
	
	}
	
	const getUrlKey = (name) => { /** 获取地址栏的参数传入字段返回值 */
	    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	    var r = window.location.search.substr(1).match(reg);
	    if (r != null) return unescape(r[2]); return null;
	}
	
	
})(window, document, jQuery)